import React, {useState, useEffect} from 'react';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import {
  Form,
  Card,
  Button,
  Row,
  Col,
  Input,
  Table,
  Tag,
  Badge,
  Popconfirm,
  Icon,
  Alert,
  message,
  Modal,
  Select
} from 'antd';
import {connect} from 'dva';
import CronAdd from "@/pages/cron/components/CronAdd";
import CronEdit from "@/pages/cron/components/CronEdit";
import CronDetails from "@/pages/cron/components/CronDetails";

const {Option} = Select;
const {confirm} = Modal;


/**
 * 定时任务
 *
 * @author zhangby
 * @date 25/2/20 11:01 am
 */

function index(props, ref) {
  const [rows, setRows] = useState([]);
  const {cron, dispatch, loading} = props;
  const [query, setQuery] = useState({});

  // 初始化
  useEffect(() => {
    queryCronList({});
  }, []);

  const queryCronList = (param) => {
    if (dispatch) {
      // 设置参数
      setQuery({...query, ...param});
      dispatch({
        type: 'cron/queryCronList',
        params: {...query, ...param},
      });
    }
  }

  const deleteCron = id => {
    if (dispatch) {
      dispatch({
        type: 'cron/deleteCron',
        params: {id: id}
      })
    }
  }

  const batchDelete = () => {
    if (rows.length === 0) {
      message.error('请选择要操作的数据');
      return;
    }
    confirm({
      title: '确定要删除选择的记录吗?',
      content: `已选择${rows.length}项记录。`,
      onOk() {
        dispatch({
          type: 'cron/deleteCron',
          params: {id: rows.join(",")}
        }).then(() => {
          setRows([]);
        })
      },
    });
  }

  return (
    <div>
      <PageHeaderWrapper subTitle="定时任务管理模块" extra={
        [
          <span key="remove">
            {
              rows.length > 0 ?
                <Button icon="delete" type="danger" onClick={batchDelete}>批量删除</Button>
                : null
            }
          </span>,
          <CronAdd key="add" queryCronList={queryCronList}/>,
        ]
      }>
        <Card id="components-table-demo-basic">
          <Row style={{marginBottom: 20}}>
            <Col span={12}>
              <span style={{fontSize: 15, fontWeight: 400}}>选择状态：</span>
              <Select defaultValue="" style={{width: 200}}
                      onChange={val => {
                        queryCronList({status: val});
                      }}
              >
                <Option value="">全部</Option>
                <Option value="0">启用</Option>
                <Option value="1">禁用</Option>
              </Select>
            </Col>
            <Col span={12} style={{textAlign: 'right'}}>
              <Input.Search
                placeholder="定时任务模糊查询"
                style={{maxWidth: 450}}
                onSearch={val => queryCronList({keyword: val})}
                enterButton
              />
            </Col>
          </Row>
          <Alert
            style={{margin: '20px 0 20px 0'}}
            message={
              <div>
                已选择{' '}
                <span style={{color: '#1690ff', fontWeight: 600, margin: '0 5px'}}>
                  {rows.length}
                </span>{' '}项
                <span style={{color: '#1690ff', marginLeft: 30, cursor: 'pointer'}}
                      onClick={() => setRows([])}>清空</span>
              </div>
            }
            type="info"
            showIcon
          />
          {/* 数据列表 */}
          <Table
            dataSource={cron.list}
            scroll={{x: 900}}
            loading={loading}
            pagination={
              {
                pageSize: cron.pagination.pageSize,
                current: cron.pagination.current,
                total: cron.pagination.total,
                onChange: (page, pageSize) => {
                  queryCronList({pageNum: page, pageSize: pageSize})
                },
              }
            }
            rowKey="id"
            rowSelection={{
              selectedRowKeys: rows,
              onChange: keys => setRows(keys),
            }}
            columns={
              [
                {
                  title: '名称',
                  dataIndex: 'name',
                  align: 'left',
                  render: (val, record) => (
                    <CronEdit cronId={record.id}>
                      <Button type="link" style={{paddingLeft: 0}}>{val}</Button>
                    </CronEdit>
                  )
                },
                {
                  title: '标识',
                  dataIndex: 'mark',
                  align: 'center',
                  render: val => (
                    <span style={{color: '#c41d7f'}}>{val}</span>
                  )
                },
                {
                  title: 'Cron 表达式',
                  dataIndex: 'cron',
                  align: 'center',
                  render: (val, record) => (
                    <div>
                      <CronDetails cron={record}>
                        <Button type="link" style={{paddingLeft: 0}}>{val}（ {record.tails.cronStatus.label} ）</Button>
                      </CronDetails>
                      {
                        record.tails.currentCron && val !== record.tails.currentCron ?
                          <div style={{ color: '#c41d7f', fontSize: 11 }}>当前频率: {record.tails.currentCron}</div>
                        : null
                      }
                    </div>
                  )
                },
                {
                  title: '状态',
                  dataIndex: 'status',
                  align: 'center',
                  render: val => (
                    <div>
                      {val === '0' ?
                        <span style={{color: '#108ee9'}}>
                          <Badge status="processing"/>启用
                        </span>
                        :
                        <span style={{color: '#f50'}}>
                          <Badge status="error"/>停用
                        </span>
                      }
                    </div>
                  )
                },
                {
                  title: '创建时间',
                  dataIndex: 'createDate',
                  align: 'center',
                  render: val => (
                    <Tag.CheckableTag>{val}</Tag.CheckableTag>
                  )
                },
                {
                  title: '备注信息',
                  dataIndex: 'remarks',
                  align: 'left',
                  render: val => (
                    <Tag.CheckableTag>{val}</Tag.CheckableTag>
                  )
                },
                {
                  title: '操作',
                  dataIndex: 'id',
                  align: 'center',
                  render: (val, record) => (
                    <div>
                      <CronEdit cronId={val}/>
                      {/* 删除 */}
                      <Popconfirm
                        onConfirm={() => deleteCron(val)}
                        title="确定要删除记录吗？"
                        icon={<Icon type="question-circle-o" style={{color: 'red'}}/>}
                      >
                        <Button
                          style={{marginLeft: 10}}
                          type="danger"
                          shape="circle"
                          icon="delete"
                        />
                      </Popconfirm>
                    </div>
                  )
                },
              ]
            }
          />
        </Card>
      </PageHeaderWrapper>
    </div>
  )

}

const form = Form.create({name: 'index',})(index)

export default connect(({cron, loading}) => ({
  cron: cron,
  loading: cron.loading
}))(form);

